package com.uduemc.biso.web.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import com.uduemc.biso.web.component.MyAccessDeniedHandler;
import com.uduemc.biso.web.component.MyAuthenticationFailureHandler;
import com.uduemc.biso.web.component.MyAuthenticationSuccessHandler;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
	/**
	 * 配置加密、验证密码方法
	 * 需要配置实现 PasswordEncoder 接口类
	 * BCryptPasswordEncoder 是内置的加密方法，推荐使用
	 * @return
	 */
	@Bean
	public PasswordEncoder passwordEncoder() {
		return new BCryptPasswordEncoder();
	}
	
	// 验证成功时的 handle
	@Autowired
	private MyAuthenticationSuccessHandler myAuthenticationSuccessHandler;
	
	// 验证失败是的 handle
	@Autowired
	private MyAuthenticationFailureHandler myAuthenticationFailureHandler;
	
	// 验证失败是的 handle
	@Autowired
	private MyAccessDeniedHandler myAccessDeniedHandler;
	
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		
		http.formLogin()
			.loginPage("/login")
			.loginProcessingUrl("/login")
			.successHandler(myAuthenticationSuccessHandler)
			.failureHandler(myAuthenticationFailureHandler)
		.and()
			.authorizeRequests()
			.antMatchers("/manage/**").authenticated()
			.anyRequest().permitAll()
		.and()
			.sessionManagement()	
			// .invalidSessionUrl("/session/invalid") // session 失效跳转连接
		.and()
			.logout()
			.logoutUrl("/logout")
		.and()
			.exceptionHandling().accessDeniedHandler(myAccessDeniedHandler);
	}
	
	/**
	 * ignoring 是完全绕过了spring security的所有filter，相当于不走spring security
	 * permitAll 没有绕过spring security，其中包含了登录的以及匿名的。
	 * 这里这么做只是将获取主控端的数据端口放行
	 */
	@Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/api/node/**");
    }
}
